package org.funmodelling;

import java.awt.*;
import java.awt.event.*;

import javax.media.opengl.*;
import com.sun.opengl.util.*;
import java.nio.IntBuffer;
import java.util.*;
import java.util.ArrayList;
import javax.media.opengl.glu.GLU;
import javax.swing.JOptionPane;

/**
 * SimpleJOGL.java <BR>
 * author: Brian Paul (converted to Java by Ron Cemer and Sven Goethel) <P>
 *
 * This version is equal to Brian Paul's version 1.2 1999/10/21
 */
public class SimpleJOGL64 implements GLEventListener,KeyListener, MouseListener, MouseMotionListener, MouseWheelListener {

    private float x = 0.0f, y = -3.0f, z = -5.0f;
    private float rx = -90.0f, ry = 0.0f, rz = 0.0f;
    private float zoomFactor = 1.0f;

    private static VModel model;
    private ArrayList<Slice> slices;
    private int modelGLId;

    private GLU glu = new GLU();
    private boolean isMouseClicked = false;
    private static final int BUFSIZE = 12;
    private Point pickpoint= new Point();
    private Vertex selectedVertex;

    public static void main(String[] args) {

        //load data from files
        model = DataLoader.LoadFromFile("points.txt", "midpoints.txt");

        Frame frame = new Frame("Simple Vein Model");
        GLCanvas canvas = new GLCanvas();

        canvas.addGLEventListener(new SimpleJOGL64());
        frame.add(canvas);
        frame.setSize(640, 480);
        final Animator animator = new Animator(canvas);
        frame.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                // Run this on another thread than the AWT event queue to
                // make sure the call to Animator.stop() completes before
                // exiting
                new Thread(new Runnable() {

                    public void run() {
                        animator.stop();
                        System.exit(0);
                    }
                }).start();
            }
        });
        // Center frame
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        canvas.requestFocusInWindow();
        animator.start();
    }

    public void init(GLAutoDrawable drawable) {
        // Use debug pipeline
        // drawable.setGL(new DebugGL(drawable.getGL()));

        GL gl = drawable.getGL();

        System.err.println("INIT GL IS: " + gl.getClass().getName());
        System.err.println("Chosen GLCapabilities: " +
                drawable.getChosenGLCapabilities());
        // Enable VSync
        gl.setSwapInterval(1);

        // Clear the drawing area
        gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);

        //initially draw points
        slices = model.getSlices();
        int msize = model.size();

        Slice s;
        Vertex v;
        ArrayList<Vertex> vList;
        Stack<Vertex> vStck = new Stack<Vertex>();

        int vlen,ssize;
        modelGLId = gl.glGenLists(1);
        gl.glNewList(modelGLId, GL.GL_COMPILE);
        //gl.glPointSize(3.0f);
        gl.glBegin(GL.GL_POINTS);
        gl.glColor3f(1.0f, 0.0f, 0.0f);//red

        for (int i = 0; i < msize; i++) {
            s = slices.get(i);
            ssize = slices.size();
            for (int j = 0; j < ssize; j++) {
                vList = s.getVertices();
                vlen = vList.size();
                for(int k=0; k<vlen; k++)
                {
                   v = vList.get(k);
                   gl.glVertex3f(v.X, v.Y, v.Z);
                }
            }
            v = s.getMidPoint();
            vStck.push(v);
        }
        gl.glEnd();//Points

        //Midpoints
        gl.glBegin(GL.GL_LINE_STRIP);
        gl.glColor3f(0.0f, 1.0f, 0.0f);//green
        while(!vStck.isEmpty())
        {
            v = vStck.pop();
            gl.glVertex3f(v.X, v.Y, v.Z);
        }

        gl.glEnd();//Lines

        gl.glEndList();
        gl.glEnable(GL.GL_NORMALIZE);

        //Listeners binding
        drawable.addKeyListener(this);
        drawable.addMouseListener(this);
        drawable.addMouseMotionListener(this);
        drawable.addMouseWheelListener(this);
    }

    public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {
//        GL gl = drawable.getGL();
//
//        float h = (float) height / (float) width;
//
//        gl.glMatrixMode(GL.GL_PROJECTION);
//
//        System.err.println("GL_VENDOR: " + gl.glGetString(GL.GL_VENDOR));
//        System.err.println("GL_RENDERER: " + gl.glGetString(GL.GL_RENDERER));
//        System.err.println("GL_VERSION: " + gl.glGetString(GL.GL_VERSION));
//        gl.glLoadIdentity();
//        gl.glFrustum(-1.0f, 1.0f, -h, h, 1.0f, 1000.0f);
//        gl.glMatrixMode(GL.GL_MODELVIEW);
//        gl.glLoadIdentity();
//        gl.glTranslatef(0.0f, 0.0f, -40.0f);
        GL gl = drawable.getGL();
        glu = new GLU();

        if (height <= 0) { // avoid a divide by zero error!

            height = 1;
        }
        final float h = (float) width / (float) height;
        gl.glViewport(0, 0, width, height);
        gl.glMatrixMode(GL.GL_PROJECTION);
        gl.glLoadIdentity();
        glu.gluPerspective(45.0f, h, 1.0, 1000.0);
        gl.glMatrixMode(GL.GL_MODELVIEW);
        gl.glLoadIdentity();
    }

    public void display(GLAutoDrawable drawable) {

        GL gl = drawable.getGL();

        // Special handling for the case where the GLJPanel is translucent
        // and wants to be composited with other Java 2D content
        if ((drawable instanceof GLJPanel) &&
                !((GLJPanel) drawable).isOpaque() &&
                ((GLJPanel) drawable).shouldPreserveColorBufferIfTranslucent()) {
            gl.glClear(GL.GL_DEPTH_BUFFER_BIT);
        } else {
            gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
        }
        if(isMouseClicked)
        {
            drawSceneInSelectMode(gl);
            isMouseClicked = false;
        }
        drawScene(gl, GL.GL_RENDER);
        // Flush all drawing operations to the graphics card
        gl.glFlush();
    }

    public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) {
    }

    /*Assumes Tetrahedron edge 0.002f*/
    private void drawScene(GL gl, int mode){
        gl.glPushMatrix();

        gl.glTranslatef(x, y, z);
        gl.glRotatef(rx, 1.0f, 0.0f, 0.0f);
        gl.glRotatef(ry, 0.0f, 1.0f, 0.0f);
        gl.glRotatef(rz, 0.0f, 0.0f, 1.0f);
        gl.glScalef(zoomFactor, zoomFactor, zoomFactor);


        gl.glPushMatrix();
        gl.glCallList(modelGLId);
        gl.glPopMatrix();

        //draw midline selection tetrahedrons
        drawSelectionPoints(gl, mode);

        if(selectedVertex != null)
        {
                drawTetrahedron(gl, 0.002f, GL.GL_SELECT, selectedVertex.Id, ModelColor.BLUE);
                drawPointer(gl, selectedVertex, ModelColor.YELLOW);
        }

        gl.glPopMatrix();
    }


    private void drawSceneInSelectMode(GL gl) {
        int selectBuf[] = new int[BUFSIZE];
        IntBuffer selectBuffer = BufferUtil.newIntBuffer(BUFSIZE);
        int hits;
        int viewport[] = new int[4];

        gl.glGetIntegerv(GL.GL_VIEWPORT, viewport, 0);

        gl.glSelectBuffer(BUFSIZE, selectBuffer);
        gl.glRenderMode(GL.GL_SELECT);

        gl.glInitNames();
        gl.glPushName(-65568);

        gl.glMatrixMode(GL.GL_PROJECTION);

        gl.glPushMatrix();
        gl.glLoadIdentity();

        glu.gluPickMatrix((double) pickpoint.x,
                          (double) (viewport[3] - pickpoint.y),
                          2,
                          2,
                          viewport,
                          0);


        glu.gluPerspective(45.0f, 1.4, 1.0, 1000.0);

        drawScene(gl, GL.GL_SELECT);

        gl.glPopMatrix();
        gl.glFlush();

        hits = gl.glRenderMode(GL.GL_RENDER);
        selectBuffer.get(selectBuf);
        processHits(hits, selectBuf);
        gl.glMatrixMode(GL.GL_MODELVIEW);
    }

    private void processHits(int hits, int buffer[]) {

        //System.out.println("hits = " + hits);

        if(hits > 0){
            int len = buffer.length;
            int id=0;

            try
            {
                for(int i=3;i<len;i+=4)
                {
                    if(buffer[i] == -65568 || buffer[i] == 0)
                        continue;
                    selectedVertex = model.getMidPointHavinId(buffer[i]);
                    id = buffer[i];

                }
                if(selectedVertex != null)
                System.out.println("Selected Vertex :" + selectedVertex.toString());
            }catch(PointNotFoundException e)
            {
                System.err.println("[ERROR]: Point Id '" + id + "' not in model!");
            }



//            System.out.print("Buffer Content [ ");
//            for(int j=0; j<len; j++)
//            {
//                System.out.print(buffer[j] + ", ");
//            }
//            System.out.print("] : End of Buffer Content.\n");
        }
    }

    private void drawTetrahedron(GL gl, float a, int mode, int id, int color) {

        if(mode == GL.GL_SELECT)
            gl.glLoadName(id);

        gl.glBegin(GL.GL_TRIANGLES);

        switch(color)
        {
            case ModelColor.RED:
                gl.glColor3f(1.0f,0.0f,0.0f);
                break;
            case ModelColor.BLUE:
                gl.glColor3f(0.0f,0.0f,1.0f);
                break;
            case ModelColor.GREEN:
                gl.glColor3f(0.0f,1.0f,0.0f);
                break;
            case ModelColor.YELLOW:
                gl.glColor3f(1.0f,1.0f,0.0f);
                break;
        }

        gl.glVertex3f(a, a, a);//1
        gl.glVertex3f(-a, -a, a);//2
        gl.glVertex3f(-a, a, -a);//3

        gl.glVertex3f(a, a, a);//1
        gl.glVertex3f(-a, a, -a);//3
        gl.glVertex3f(a, -a, -a);//4

        gl.glVertex3f(a, a, a);//1
        gl.glVertex3f(a, -a, -a);//4
        gl.glVertex3f(-a, -a, a);//2

        gl.glVertex3f(a, -a, -a);//4
        gl.glVertex3f(-a, -a, a);//2
        gl.glVertex3f(-a, a, -a);//3

        gl.glEnd();

    }

    /*>Assumes pointer length 1.0f*/
    private void drawPointer(GL gl, Vertex v, int color) {
        gl.glBegin(GL.GL_LINES);

        switch(color)
        {
            case ModelColor.RED:
                gl.glColor3f(1.0f,0.0f,0.0f);
                break;
            case ModelColor.BLUE:
                gl.glColor3f(0.0f,0.0f,1.0f);
                break;
            case ModelColor.GREEN:
                gl.glColor3f(0.0f,1.0f,0.0f);
                break;
            case ModelColor.YELLOW:
                gl.glColor3f(1.0f,1.0f,0.0f);
                break;
        }

        gl.glVertex3f(v.X - 0.5f, v.Y, v.Z);
        gl.glVertex3f(v.X + 0.5f, v.Y, v.Z);
        gl.glVertex3f(v.X, v.Y - 0.5f, v.Z);
        gl.glVertex3f(v.X, v.Y + 0.5f, v.Z);
        gl.glVertex3f(v.X, v.Y, v.Z - 0.5f);
        gl.glVertex3f(v.X, v.Y, v.Z + 0.5f);
        gl.glEnd();
    }


    /*Assumes midpoint tetrehedrons edges 0.002f */
    private void drawSelectionPoints(GL gl, int mode) {

        ArrayList<Vertex> mList = model.getMidPoints();
        Vertex v;
        int size = model.size();

        for(int i=0; i<size; i++)
        {
            v = mList.get(i);
            gl.glPushMatrix();
            gl.glTranslatef(v.X, v.Y, v.Z);
            if(v.equals(selectedVertex)){
                drawTetrahedron(gl, 0.002f, mode, v.Id, ModelColor.BLUE);
                drawPointer(gl, v, ModelColor.YELLOW);
            }
            else
                drawTetrahedron(gl, 0.002f , mode, v.Id, ModelColor.GREEN);
            gl.glPopMatrix();
        }



    }

    // Event handlers
    public void mouseDragged(MouseEvent e) {}

    public void mousePressed(MouseEvent e) {
        if (e.getButton() == MouseEvent.BUTTON1) //
        {
            pickpoint = e.getPoint();
            isMouseClicked = true;
        }
    }

    public void mouseReleased(MouseEvent e) {}

    public void mouseClicked(MouseEvent arg0) {}

    public void mouseEntered(MouseEvent arg0) {}

    public void mouseExited(MouseEvent arg0) {}

    public void mouseMoved(MouseEvent arg0) {}

    public void mouseWheelMoved(MouseWheelEvent e) {
        int notch = e.getWheelRotation();
        zoomFactor -= ((float) notch) / 5.0f;

    }

    public void keyTyped(KeyEvent e) {

    }

    public void keyPressed(KeyEvent e) {
        if (e.isControlDown() && (e.getKeyCode() == KeyEvent.VK_NUMPAD6)) {
            rx += 10;
            return;
        }
        if (e.isControlDown() && (e.getKeyCode() == KeyEvent.VK_NUMPAD4)) {
            rx -= 10;
            return;
        }
        if (e.isControlDown() && (e.getKeyCode() == KeyEvent.VK_NUMPAD8)) {
            ry += 10;
            return;
        }
        if (e.isControlDown() && (e.getKeyCode() == KeyEvent.VK_NUMPAD2)) {
            ry -= 10;
            return;
        }
        if (e.isControlDown() && (e.getKeyCode() == KeyEvent.VK_ADD)) {
            rz += 10;
            return;
        }
        if (e.isControlDown() && (e.getKeyCode() == KeyEvent.VK_SUBTRACT)) {
            rz -= 10;
            return;
        }


        if (e.getKeyCode() == KeyEvent.VK_NUMPAD6) {
            x += 0.1f;
            return;
        }
        if (e.getKeyCode() == KeyEvent.VK_NUMPAD4) {
            x -= 0.1f;
            return;
        }
        if (e.getKeyCode() == KeyEvent.VK_NUMPAD8) {
            y += 0.1f;
            return;
        }
        if (e.getKeyCode() == KeyEvent.VK_NUMPAD2) {
            y -= 0.1f;
            return;
        }
        if (e.getKeyCode() == KeyEvent.VK_ADD) {
            z += 1.0f;
            return;
        }
        if (e.getKeyCode() == KeyEvent.VK_SUBTRACT) {
            z -= 1.0f;
            return;
        }
        if (e.getKeyCode() == KeyEvent.VK_NUMPAD5) {
            x=0.0f; y=-3.0f; z=-5.0f;
            rx=-90.0f; ry=rz=0.0f;
            zoomFactor = 1.0f;
            selectedVertex = null;
            return;
        }
        
        if (e.getKeyCode() == KeyEvent.VK_F12) {
            try{

                String input = JOptionPane.showInputDialog("Midpoint ID to select:");

                int i = Integer.parseInt(input);
                Vertex v = model.getMidPointHavinId(i);
                selectedVertex = v;
                System.out.println("Selected Vertex :" + v.toString());
                
            }catch(Exception ex)
            {
            
            }
            return;
        }


    }

    public void keyReleased(KeyEvent e) {

    }
}

